﻿using AutoMapper;
using MediatR;
using NPOI.SS.Formula.Functions;
using S.Breed.Domain;
using S.Breed.Domain.Dto;
using S.Breed.Infrastructure.Interface;
using S.Breed.Read.ApI.Application.Command;
using S.Common.ApiResult;
using System.Collections.Generic;
using static S.Breed.Read.ApI.Application.Command.MaternalMatingCommand;

namespace S.Breed.Read.ApI.Application.CommandHandlers
{
    public class MaternalMatingCommandHandler : IRequestHandler<ShowMaternalMatingCommand,ApiResult<List<ShowMaternalMatingDto>>>,IRequestHandler<FanTinaCommand, MaternalMatingModel>
    {
        private readonly IMaternalMatingRepository maternalMating;
        private readonly IMapper mapper;

        public MaternalMatingCommandHandler(IMaternalMatingRepository maternalMating, IMapper mapper)
        {
            this.maternalMating = maternalMating;
            this.mapper = mapper;
        }
        /// <summary>
        /// 配种显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<ShowMaternalMatingDto>>> Handle(ShowMaternalMatingCommand request, CancellationToken cancellationToken)
        {
            var resultList = maternalMating.ShowShowMaternalMating(request.Mdate, request.Ear, request.Head);
            resultList = resultList.OrderByDescending(x => x.CreateDate).Where(t=>t.BreedState==1).ToList();

            var dto = mapper.Map<List<ShowMaternalMatingDto>>(resultList);
            ApiResult<List<ShowMaternalMatingDto>> result = new ApiResult<List<ShowMaternalMatingDto>>();
            result.Data = dto;
            result.totalCount = dto.Count;
            result.pageCount = (int)Math.Ceiling(result.totalCount * 1.0 / request.Size);
            result.Data = dto.Skip((request.Page - 1) * request.Size).Take(request.Size).ToList();
            return result;
        }
        /// <summary>
        /// 配种信息反填
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<MaternalMatingModel> Handle(FanTinaCommand request, CancellationToken cancellationToken)
        {
            var model= maternalMating.GetAll().FirstOrDefault(t=>t.BreedId==request.id);
            return model;
        }
    }
}
